﻿namespace Catalog.API.Products.CreateProduct
{
 

    public record CreateProductResult(Guid id);
    public record CreateProductCommand
        (string Name, string Description, decimal Price, string ImageFile, List<string> Categories) : ICommand<CreateProductResult>;

    public class CreateProductValidator : AbstractValidator<CreateProductCommand>
    {
        public CreateProductValidator()
        {
            RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required");
            RuleFor(x => x.Description).NotEmpty().WithMessage("Description is required");
            RuleFor(x => x.Price).GreaterThan(0).WithMessage("Price must be greater than 0");
            RuleFor(x => x.ImageFile).NotEmpty().WithMessage("ImageFile is required");
            RuleFor(x => x.Categories).NotEmpty().WithMessage("Categories is required");
        }
    }
    internal class CreateProductCommandHandler(IDocumentSession session) : ICommandHandler<CreateProductCommand, CreateProductResult>
    {
        public async Task<CreateProductResult> Handle(CreateProductCommand request, CancellationToken cancellationToken)
        {
            //创建产品
            var product = new Product
            {
                Name = request.Name,
                Description = request.Description,
                Price = request.Price,
                ImageFile = request.ImageFile,
                Categories = request.Categories
            };

            //保存产品到数据库 使用marten的IDocumentSession 进行类似于EFCore的操作
            session.Store(product);
            await session.SaveChangesAsync(cancellationToken);


            //返回产品Id
            return new CreateProductResult(product.Id);
        }
    }
}
